package com.ruoyi.system.wnjk.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.ruoyi.system.wnjk.config.AliPayConfig;
import com.ruoyi.system.wnjk.domain.vo.AlipayVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 阿里支付服务
 */
@Component
@Slf4j
public class AliPayService {

    @Autowired
    private AliPayConfig aliPayConfig;

    /**
     * 创建支付
     */
    public String createPay(AlipayVO alipayVO) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(
                aliPayConfig.getServerUrl(),
                aliPayConfig.getAppId(),
                aliPayConfig.getPrivateKey(),
                aliPayConfig.getFormat(),
                aliPayConfig.getCharset(),
                aliPayConfig.getPublicKey(),
                aliPayConfig.getSignType());
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        //异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        //同步跳转地址，仅支持http/https
        request.setReturnUrl(aliPayConfig.getReturnUrl());
        /******必传参数******/
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", alipayVO.getOutTradeNo());
        //支付金额，最小值0.01元
        bizContent.put("total_amount", alipayVO.getTotalAmount());
        //订单标题，不可使用特殊符号
        bizContent.put("subject", alipayVO.getSubject());

        /******可选参数******/
        //手机网站支付默认传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "QUICK_WAP_WAY");
        //bizContent.put("time_expire", "2022-08-01 22:00:00");

        //// 商品明细信息，按需传入
        //JSONArray goodsDetail = new JSONArray();
        //JSONObject goods1 = new JSONObject();
        //goods1.put("goods_id", "goodsNo1");
        //goods1.put("goods_name", "子商品1");
        //goods1.put("quantity", 1);
        //goods1.put("price", 0.01);
        //goodsDetail.add(goods1);
        //bizContent.put("goods_detail", goodsDetail);

        //// 扩展信息，按需传入
        JSONObject extendParams = new JSONObject();
        extendParams.put("sys_service_provider_id", alipayVO.getUserId());
        bizContent.put("extend_params", extendParams);

        request.setBizContent(bizContent.toString());
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }

        log.debug("支付宝支付返回的数据为：{}", response.getBody());

        return response.getBody();
    }

    /**
     * 查询
     */
    public String queryByTradeNo(String tradeNo) throws AlipayApiException {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(
                aliPayConfig.getServerUrl(),
                aliPayConfig.getAppId(),
                aliPayConfig.getPrivateKey(),
                aliPayConfig.getFormat(),
                aliPayConfig.getCharset(),
                aliPayConfig.getPublicKey(),
                aliPayConfig.getSignType());

        // 构造请求参数以调用接口
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
//        request.setBizContent("{\"trade_no\":\"" + tradeNo + "\"}");
//        AlipayTradeQueryResponse response = alipayClient.execute(request);
//        System.out.println(response.getBody());
//        if (response.isSuccess()) {
//
//        } else {
//            throw new RuntimeException("Failed to query order status: " + response.getSubCode());
//        }

//
        // 设置订单支付时传入的商户订单号
        System.out.println("订单号="+tradeNo);
//        model.setOutTradeNo("1895088914861998082");
        model.setOutTradeNo(tradeNo);
        // 设置查询选项
        List<String> queryOptions = new ArrayList<String>();
        queryOptions.add("trade_settle_info");
        model.setQueryOptions(queryOptions);

        request.setBizModel(model);
        // 第三方代调用模式下请设置app_auth_token
        // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");

        AlipayTradeQueryResponse response = alipayClient.execute(request);
        System.out.println(response.getBody());
        Map map = JSONObject.parseObject(response.getBody(), Map.class);

        //获取内层的json数据
        Object o = map.get("alipay_trade_query_response");
        Map mapData = JSONObject.parseObject(o+"", Map.class);
        System.out.println(map.toString());
        //获取交易状态
        Object resStatus = mapData.get("trade_status");
        if (resStatus == null){
            return "error";
        }
        return resStatus.toString();
//        if (response.isSuccess()) {
//            System.out.println("调用成功");
//        } else {
//            System.out.println("调用失败");
//            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
//            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
//            // System.out.println(diagnosisUrl);
//        }
    }
}
